package com.ruoyi.mobile.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.mobile.domain.SysDeptEntity;
import com.ruoyi.mobile.domain.SysUserEntity;
import com.ruoyi.mobile.mapper.ISysDeptMapper;
import com.ruoyi.mobile.mapper.ISysUserMapper;
import com.ruoyi.mobile.utils.NftResponse;
import com.ruoyi.mobile.utils.QueryUtil;
import com.ruoyi.mobile.utils.ResponseConstants;
import com.ruoyi.system.api.req.LoginReq;
import com.ruoyi.system.api.req.SysUserReq;
import com.ruoyi.system.api.resp.LoginResp;
import com.ruoyi.system.api.resp.SysDeptResp;
import com.ruoyi.system.api.resp.SysUserResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.mobile.service.ISysUserService;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<ISysUserMapper, SysUserEntity> implements ISysUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISysDeptMapper sysDeptMapper;

    @Override
    public NftResponse<SysUserResp> getUserAppInfoByPhone(String appid, String phone) {
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("delFlag"), "0");
        wrapper.eq(QueryUtil.camelToUnderline("phonenumber"), phone);
        List<SysUserEntity> users = this.baseMapper.selectList(wrapper);
        if (users==null||users.size()<=0) {
            SysUserEntity sysUserEntity = new SysUserEntity();
            sysUserEntity.setPhonenumber(phone);
            sysUserEntity.setUserName("获取姓名");
            sysUserEntity.setCreateTime(DateUtils.getNowDate());
            sysUserEntity.setYwType("3");
            sysUserEntity.setAppId(appid);
            Integer result = this.baseMapper.insert(sysUserEntity);
            if (result>0) {
                SysUserResp userResp = BeanUtil.copyProperties(sysUserEntity, SysUserResp.class);
                return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userResp);
            }else {
                return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此人", null);
            }
        }
        SysUserResp userAppResp = BeanUtil.copyProperties(users.get(0), SysUserResp.class);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userAppResp);
    }

    @Override
    public NftResponse<SysUserResp> getUserAppInfoById(Long userId) {
        SysUserEntity userAppEntity = this.baseMapper.selectById(userId);
        if (userAppEntity == null) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "查无此人", null);
        }
        SysUserResp userAppResp = BeanUtil.copyProperties(userAppEntity, SysUserResp.class);
        SysUserResp rtn = this.baseMapper.getUserInfo(userAppEntity.getUserId());
        if (null!=rtn&&null!=rtn.getUserId()) {
            userAppResp.setIsManager(true);
        }else {
            userAppResp.setIsManager(false);
        }
        userAppResp.setPhone(userAppResp.getPhonenumber());
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", userAppResp);
    }

    @Override
    public NftResponse<Boolean> updateUserAppInfo(SysUserReq query) {
        if (query.getUserId() == null || query.getUserId() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "系统错误", null);
        }
        Object redisLoginInfoObj = redisTemplate.opsForValue().get("userinfo-app:" + query.getUserId());
        if (redisLoginInfoObj == null) {
            return new NftResponse<>(ResponseConstants.TOKEN_CODE, "请重新登录", null);
        }
        LoginResp redisLoginInfo = JSONUtil.toBean(redisLoginInfoObj.toString(), LoginResp.class);
        if (redisLoginInfo == null) {
            return new NftResponse<>(ResponseConstants.TOKEN_CODE, "请重新登录", null);
        }
        QueryWrapper<SysDeptEntity> wrapperQueryDept = new QueryWrapper<>();
        wrapperQueryDept.ne(QueryUtil.camelToUnderline("parentId"), "0");
        wrapperQueryDept.eq(QueryUtil.camelToUnderline("status"), "0");
        wrapperQueryDept.eq(QueryUtil.camelToUnderline("deptName"), query.getShop());
        List<SysDeptEntity> deptList = sysDeptMapper.selectList(wrapperQueryDept);
        List<SysDeptResp> deptResult = BeanUtil.copyToList(deptList, SysDeptResp.class);
        Boolean result = true;
        SysUserResp postXsResp = this.baseMapper.getStudentPostInfo();
        if (null!=deptResult&&deptResult.size()>0) {
            query.setDeptId(deptResult.get(0).getDeptId());
            QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
            wrapper.eq(QueryUtil.camelToUnderline("phonenumber"), redisLoginInfo.getPhone());
            wrapper.eq(QueryUtil.camelToUnderline("deptId"), query.getDeptId());
            wrapper.eq(QueryUtil.camelToUnderline("delFlag"),"0");
            wrapper.eq(QueryUtil.camelToUnderline("status"), "0");
            Long userCount = this.baseMapper.selectCount(wrapper);
            if(userCount > 0) {
                result = updateById(BeanUtil.copyProperties(query, SysUserEntity.class));
            }else {
                SysUserEntity sysUserEntity = new SysUserEntity();
                sysUserEntity.setPhonenumber(redisLoginInfo.getPhone());
                sysUserEntity.setUserName(query.getUserName());
                sysUserEntity.setCreateTime(DateUtils.getNowDate());
                sysUserEntity.setDeptId(query.getDeptId());
                sysUserEntity.setHopenId(redisLoginInfo.getOpenId());
                sysUserEntity.setYwType(query.getYwType());
                sysUserEntity.setAppId(query.getAppId());
                this.baseMapper.insert(sysUserEntity);

                List<SysUserEntity> userList = this.baseMapper.selectList(wrapper);
                if (null!=userList&&userList.size()>0) {
                    SysUserResp roleXsResp = this.baseMapper.getStudentRoleInfo();
                    this.baseMapper.insertUserPost(userList.get(0).getUserId(), postXsResp.getPostId());
                    this.baseMapper.insertUserRole(userList.get(0).getUserId(), roleXsResp.getRoleId());
                }
            }
        }else {
            result = updateById(BeanUtil.copyProperties(query, SysUserEntity.class));
        }
        QueryWrapper<SysUserEntity> wrapperUser = new QueryWrapper<>();
        wrapperUser.eq(QueryUtil.camelToUnderline("phonenumber"), redisLoginInfo.getPhone());
        wrapperUser.eq(QueryUtil.camelToUnderline("delFlag"),"0");
        wrapperUser.eq(QueryUtil.camelToUnderline("status"), "0");
        List<SysUserEntity> userList = this.baseMapper.selectList(wrapperUser);
        for (SysUserEntity user:userList) {
            if (user.getUserId().longValue()!=query.getUserId().longValue()) {
                user.setYwType(query.getYwType());
                user.setAppId(query.getAppId());
                updateById(user);
            }
        }
        SysUserResp userpostResp = this.baseMapper.getUserPostInfo(query.getUserId());
        if (null==userpostResp) {
            this.baseMapper.insertUserPost(query.getUserId(), postXsResp.getPostId());
        }
        if (!result) {
            return new NftResponse(ResponseConstants.ERROR_CODE, "保存失败", false);
        }
        redisService.delCacheMap("USER:DP");
        return new NftResponse(ResponseConstants.SUCCESS_CODE, "保存成功", true);
    }

    @Override
    public NftResponse<Boolean> resetPass(LoginReq loginReq) {
        this.baseMapper.updateUserPassByUserId(SecurityUtils.encryptPassword(loginReq.getPassword()),loginReq.getUserId());
        return new NftResponse(ResponseConstants.SUCCESS_CODE, "修改成功", true);
    }
}
